package com.ebupt.migu.music.userGroup.service.impl;

import com.ebupt.migu.music.common.constants.UserGroupConstants;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.userGroup.mapper.CrowdMapper;
import com.ebupt.migu.music.userGroup.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Intellij IDEA.
 * User:  liuyangyang@cd.ebupt.com
 * Date:  2019/9/10
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private CrowdMapper crowdMapper;

    // 文件默认保存路径
    @Value("${path.file_upload}")
    private String FILE_UPLOAD_PATH;

    /**
     * 文件上传
     *
     * @param fileToUpload
     * @return
     */
    @Override
    public ResultObject uploadCSVFile(MultipartFile fileToUpload) {
        ResultObject<Map<String, String>> res = new ResultObject<>();
        // 校验文件是否为空，格式是否正常
        boolean isCSVFile = CSVUtils.validateUploadFile(fileToUpload, "csv");
        if (!isCSVFile) {
            throw new MyException(StatusEnum.UPLOAD, "文件格式或内容异常！");
        }
        // 获取原始文件名
        String oriName = fileToUpload.getOriginalFilename();
        Date date = new Date();
        // 重命名
        String reName = FILE_UPLOAD_PATH + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS) + ".csv";
        //直接保存到指定目录
        CSVUtils.upload(fileToUpload, reName);
        Map<String, String> map = new HashMap<>(3);
        map.put("reName", reName);
        map.put("oriName", oriName);
        map.put("ftpDir", FILE_UPLOAD_PATH);
        res.setMsg("文件上传成功！");
        res.setData(map);
        return res;
    }

    /**
     * 删除指定文件
     *
     * @param params
     * @return
     */
    @Override
    public ResultObject deleteCSVFile(Map<String, Object> params) {
        String reName = params.get("reName").toString();
        File file = new File(reName);
        if (!file.exists()) {
            throw new MyException(StatusEnum.BUSINID, "文件不存在！");
        }
        file.delete();
        ResultObject res = new ResultObject();
        res.setMsg("删除成功！");
        return res;
    }

    /**
     * 创建用户群
     *
     * @return
     */
    @Override
    public ResultObject createUserGroup(Map<String, Object> params) {
        Date date = new Date();
        String userGroupName = params.get("userGroupName").toString();
        // 判断人群名称是否存被占用
        Map<String, Object> map = new HashMap<>();
        map.put("userGroupName", userGroupName);
        if (crowdMapper.isUserGroupNameExistCnt(map) > 0) {
            throw new MyException(StatusEnum.NAME_ALREADY_EXIST, "人群名称被占用，请尝试换一个人群名称！");
        }
        // 生成用户群ID
        String groupId = "DR" + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        // 判断为FTP同步方式时，文件是否已经上传
        String isFtp = params.get("isFtp").toString();
        if (UserGroupConstants.IS_FTP.equals(isFtp)) {
            String filepath = params.get("fileOriname").toString();
            File file = new File(filepath);
            if (!file.exists()) {
                throw new MyException(StatusEnum.FILE_NOT_EXISTS, "");
            }
            groupId = "TB" + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        }
        params.put("groupId", groupId);
        // 创建方式-以文件上传方式创建
        if (params.get("createWay")!=null&&!params.get("createWay").toString().equals("10")){
            params.put("createWay", UserGroupConstants.CREATE_BY_FILE_UPLOAD);
            //如果备注为空，则将文件名称保存到备注中
            if (params.get("createDesc")==null||
                    StringUtils.isBlank(params.get("createDesc").toString())){
                params.put("createDesc",params.get("fileOriname").toString().
                        substring(params.get("fileOriname").toString().lastIndexOf("/")+1));
            }
        }
        // 创建状态-创建中
        params.put("createStatus", UserGroupConstants.BEING_CREATED);
        // 仅短信运营，不需要反查,直接保存人群
        if (null != params.get("onlySms") && params.get("onlySms").toString().equals("1")) {
            // TODO
        }
        try {
            crowdMapper.createUserGroup(params);
            crowdMapper.createUserFtpDetail(params);
        } catch (Exception e) {
            log.error("创建用户群失败", e);
            throw new MyException(StatusEnum.CREATE_USER_GROUP_ERROR, "创建用户群失败");
        }
        ResultObject res = new ResultObject();
        res.setMsg("创建成功！");
        return res;
    }

    /**
     * 创建用户群
     *
     * @return
     */
    @Override
    public ResultObject createValueUserGroup(Map<String, Object> params) {
        Date date = new Date();
        String userGroupName = params.get("userGroupName").toString();
        // 判断人群名称是否存被占用
        Map<String, Object> map = new HashMap<>();
        map.put("userGroupName", userGroupName);
        if (crowdMapper.isUserGroupNameExistCnt(map) > 0) {
            throw new MyException(StatusEnum.NAME_ALREADY_EXIST, "人群名称被占用，请尝试换一个人群名称！");
        }
        // 生成用户群ID
        String groupId = "ZD" + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        params.put("groupId", groupId);
        // 创建状态-创建中
        params.put("createStatus", UserGroupConstants.BEING_CREATED);
        try {
            crowdMapper.createUserGroup(params);
        } catch (Exception e) {
            log.error("创建用户群失败", e);
            throw new MyException(StatusEnum.CREATE_USER_GROUP_ERROR, "创建用户群失败");
        }
        ResultObject res = new ResultObject();
        res.setMsg("创建成功！");
        return res;
    }

    /**
     * 创建用户群-生命周期（用户实时人群）
     * @param params
     * @return
     */
    @Override
    public ResultObject createUserLifeCycle(Map<String, Object> params) {
        Date date = new Date();
        String userGroupName = params.get("userGroupName").toString();
        // 判断人群名称是否存被占用
        Map<String, Object> map = new HashMap<>(2);
        map.put("userGroupName", userGroupName);
        if (crowdMapper.isUserGroupNameExistCnt(map) > 0) {
            throw new MyException(StatusEnum.NAME_ALREADY_EXIST, "人群名称被占用，请尝试换一个人群名称！");
        }
        // 生成用户群ID
        String groupId = "UL" + DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        params.put("groupId", groupId);
        // 创建状态-创建中
        params.put("createStatus", UserGroupConstants.BEING_CREATED);
        try {
            crowdMapper.createUserGroup(params);
        } catch (Exception e) {
            log.error("创建用户群失败", e);
            throw new MyException(StatusEnum.CREATE_USER_GROUP_ERROR, "创建用户群失败");
        }
        ResultObject res = new ResultObject();
        res.setMsg("创建成功！");
        return res;
    }


}
